<?PHP
require_once('../database/database.class.php');
require_once('user.class.php');

class UserManager
{
	const REQUEST_SUCCESS = 0;
	const USERNAME_FAILURE = 1;
	const PASSWORD_FAILURE = 2;
	const EMAIL_FAILURE = 3;
	
	const PASS_MIN_LEN = 6;
	const USER_MIN_LEN = 2;
	const USER_MAX_LEN = 15;
	
	private static $instance;
	private $connection;
	private $users = Array();
	
	private function __construct(){}
	public function __destruct()
	{
	}
	
	public static function getInstance()
	{
		if(!isset(self::$instance))
		{
			$class = __CLASS__;
			self::$instance = new $class;
		}
		return self::$instance;
	}
	
	public function getUser($username,$password)
	{
		$db = Database::getInstance();
		$db->connect();
		
		$u = $db->selectAssoc("SELECT id, password FROM users WHERE username='$username'");
		if(count($u) > 0)
		{
			if(md5($password) == $u[0]['password'])
			{
				//Logged in
				$user = new User();
				$users[$id] = $user;
				return $user;
			}
			else
			{
				//Wrong password
				return false;
			}
		}
		
		//Wrong username
		return false;
	}
	
	public function checkUsername($username)
	{
		if(isset($username))
		{
			$db = Database::getInstance();
			$db->connect();
	
			$count = $db->count('users',Array('username'=>$username));
			return ($count==0);
		}
		
		return false;
	}
	
	public function createUser($username,$password,$email)
	{
		if(!$this->validateUsername($username))
		{
			return UserManager::USERNAME_FAILURE;
		}
		
		if(!$this->validateEmail($email))
		{
			return UserManager::EMAIL_FAILURE;
		}
		
		if(!$this->validatePassword($password))
		{
			return UserManager::PASSWORD_FAILURE;
		}
		
		$db = Database::getInstance();
		$db->connect();
						
		$db->insert('users',Array('username'=>$username,'password'=>md5($password),'category'=>0,'email'=>$email));
		
		return UserManager::REQUEST_SUCCESS;
	}
	
	private function validatePassword($pass)
	{
		if(strlen($pass) < UserManager::PASS_MIN_LEN)
		{
			return false;
		}
		
		return true;
	}
	
	private function validateEmail($email)
	{
		if(strpos($email,'@') == false || strpos($email,'.') == false)
		{
			return false;
		}
		
		return true;
	}
	
	private function validateUsername($uname)
	{
		if(strlen($uname) < UserManager::USER_MIN_LEN || strlen($uname) > UserManager::USER_MAX_LEN)
		{
			return false;
		}
		
		if(!$this->checkUsername($uname))
		{
			return false;
		}
		
		return true;
	}
}
?>